<template>
  <div class="write-top">
    <!--    顶部按钮-->
    <div class="top-btn">
      <div class="btn-left">
        <el-button class="active" :disabled="isLoading" @click="sendEmail('')" style=" line-height: 29px"><i class="icon-fasong iconfont"></i>发送
        </el-button>
        <el-button @click="sendEmail(2)" :disabled="isLoading">存草稿</el-button>
        <el-button @click="toApproval"  :disabled="isLoading">提交审批</el-button>
        <el-button @click="toReview">预 览</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div class="btn-right">
        <a href="javascript:void(0)" v-show="!isGroupSend" style="color: #409EFF">
          <el-button type="text" @click="ToCarbonCopy">{{now.isCarbonCopy?"取消抄送":'添加抄送'}}</el-button>
          |
          <el-button type="text" @click="ToSecretDelivery" style="margin-left: 5px">
            {{now.isSecretDelivery?"取消密送":'添加密送'}}
          </el-button>
          |
        </a>
        <el-button type="text" @click="groupSend">{{isGroupSend?'取消':''}}群发单显</el-button>
      </div>
    </div>
    <div class="line">
      <span class="label">发件人：</span>
      <el-select class="myInput" v-model="senderEmailElse" @change="dealSend" size="small">
        <el-option v-for="item in common.emailList" :label="item.emailAddr" :value="item.emailAddr"></el-option>
      </el-select>
    </div>
    <div class="line">
      <span class="label" :style="{width:isGroupSend?'71px':'57px'}">{{isGroupSend?'群发单显':'收件人'}}：</span>
      <div class="line-content">
        <el-tag v-for="item,index in now.addresseeEmail"
                :key="index"
                closable @close="handleClose(item,1)"
                type="success">
          {{item.linker}}<{{item.email}}>
        </el-tag>
        <div class="input-add">
          <el-autocomplete size="small" v-if="now.addresseeEmail.length<30" class="inline-input"
                           v-model="receiveUser" :style="{borderBottom: isWrong?'1px solid red':'1px solid transparent'}"
                           :fetch-suggestions="querySearch" placeholder="点击选择收件人或输入收件人邮箱" :trigger-on-focus="false"
                           @blur="addUser('收件人',receiveUser)" @keyup.enter.native="addUser('收件人',receiveUser)"
                           @select="handleSelect">
            <template slot-scope="{ item }">
              <span class="man-who">
                <img v-if="item.type" src="../../../../public/img/email/icon/icon-customer.png" alt="">
                 <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">{{item.linkMan}}
              </span>
            </template>
          </el-autocomplete>
          <b @click="addUser('收件人',receiveUser)" v-show="receiveUser!=''">添加</b>
        </div>
      </div>
      <span class="addMan" @click="showDialog(1)">添加收件人</span>
    </div>
    <div class="area-time" v-if="now.addresseeEmail.length==30" style="color: #232323">
      （ 请确认您的收件人均为有效收件邮箱，收件人每次最多群发30人！）
    </div>
    <div class="area-time" v-if="isGroupSend" style="color: red">
      （ 请确认您的收件人均为有效收件邮箱，否则将有封号风险！群发单显每日限制使用次数4次，每次最多群发30人！）
    </div>
    <div class="line" v-if="now.isCarbonCopy">
      <span class="label">抄&nbsp;&nbsp;&nbsp;送：</span>
      <div class="line-content">
        <el-tag v-for="item,index in now.emailCarbonCopy"
                :key="index"
                closable @close="handleClose(item,2)"
                type="success">
          {{item.linker}}<{{item.email}}>
        </el-tag>
        <div class="input-add">
          <el-autocomplete size="small" v-if="now.emailCarbonCopy.length<20"
                           class="inline-input"
                           v-model="copyUser" :style="{borderBottom: isWrong2?'1px solid red':'1px solid transparent'}"
                           :fetch-suggestions="querySearch2" @blur="addUser('抄送',copyUser)" @keyup.enter.native="addUser('抄送',copyUser)"
                           placeholder="输入抄送邮箱/点击添加按钮选择抄送"
                           :trigger-on-focus="false"
                           @select="handleSelect2">
            <template slot-scope="{ item }">
              <span class="man-who"> <img v-if="item.type" src="../../../../public/img/email/icon/icon-customer.png" alt="">
                 <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">{{item.linkMan}}</span>
            </template>
          </el-autocomplete>
          <b @click="addUser('抄送',copyUser)" v-show="copyUser!=''">添加</b>
        </div>
      </div>
      <span class="addMan" @click="showDialog(2)">添加抄送</span>
    </div>
    <div class="area-time" v-if="now.emailCarbonCopy.length==20" style="color: #232323">
      （ 请确认您的收件人均为有效收件邮箱，抄送人每次最多群发20人！）
    </div>
    <div class="line" v-if="now.isSecretDelivery">
      <span class="label">密&nbsp;&nbsp;&nbsp;送：</span>
      <div class="line-content">
        <el-tag v-for="item,index in now.emailSecretDelivery"
                :key="index"
                closable @close="handleClose(item,3)"
                type="success">
          {{item.linker}}<{{item.email}}>
        </el-tag>
        <div class="input-add">
          <el-autocomplete size="small" v-if="now.emailSecretDelivery.length<20"
                           class="inline-input" @blur="addUser('密送',secretUser)" @keyup.enter.native="addUser('密送',secretUser)"
                           v-model="secretUser" :style="{borderBottom: isWrong3?'1px solid red':'1px solid transparent'}"
                           :fetch-suggestions="querySearch3"
                           placeholder="输入密送邮箱/点击添加按钮选择密送"
                           :trigger-on-focus="false"
                           @select="handleSelect3">
            <template slot-scope="{ item }">
              <span class="man-who">  <img v-if="item.type" src="../../../../public/img/email/icon/icon-customer.png" alt="">
                 <img v-else src="../../../../public/img/email/icon/icon-people.png" alt="">{{item.linkMan}}</span>
            </template>
          </el-autocomplete>
          <b @click="addUser('密送',secretUser)" v-show="secretUser!=''">添加</b>
        </div>
      </div>
      <span class="addMan" @click="showDialog(3)">添加密送</span>
    </div>
    <div class="area-time" v-if="now.emailSecretDelivery.length==20" style="color: #232323">
      （ 请确认您的收件人均为有效收件邮箱，密送人每次最多群发20人！）
    </div>
    <div class="line" style="padding: 0">
      <span class="label">主&nbsp;&nbsp;&nbsp;题：</span> <input class="myInput" type="text" v-model="now.emailSubject"
                                                              placeholder="请输入主题">
    </div>
    <!--弹框-->
    <!--    添加联系人-->
    <DialogConcat ref="dialogConcat" @getConcat="getConcat"></DialogConcat>
  </div>
</template>

<script>
    import {mapState} from 'vuex'
    import DialogConcat from "@/components/mail/DialogConcat";
    import {validateEmail} from '@/util/util'
    import {getCustomerSuggest} from '@/api/mail/write'

    export default {
        name: "Write",
        props: ['senderEmail', 'defaultMail','isLoading'],
        components: {DialogConcat},
        data() {
            return {
                now: {
                    addresseeEmail: [],//收件人
                    isCarbonCopy: false,
                    emailCarbonCopy: [],//抄送
                    isSecretDelivery: false,
                    emailSecretDelivery: [],//密送
                    emailSubject: '',//主题
                },
                isGroupSend: false,//群发单显
                old: {//原数据
                    addresseeEmail: [],
                    isCarbonCopy: false,  //抄送
                    emailCarbonCopy: [],
                    isSecretDelivery: false,//密送
                    emailSecretDelivery: []
                },
                dialog: {
                    title: ''
                },
                contactList: [],
                selectEmail: [],//已选邮箱
                senderEmailElse: '',
                receiveUser: '',//添加收件人
                copyUser: '',//抄送
                secretUser: '',//密送
                isBack: false,
                isWrong:false,
                isWrong2:false,
                isWrong3:false,
            }
        },
        computed: {
            ...mapState(['common'])
        },
        mounted() {
            this.bus.$on('titleNickname', () => {
                this.now.emailSubject = 'Dear:#nickname#' + this.now.emailSubject;
            })
        },
        methods: {
            handleSelect(item) {//收件人
                this.receiveUser = item.email;
                this.addUser('收件人', this.receiveUser);
            },
            handleSelect2(item){
                this.copyUser = item.email;
                this.addUser('抄送', this.copyUser);
            },
            handleSelect3(item){
                this.secretUser = item.email;
                this.addUser('密送', this.secretUser);
            },
            init(params) {
                if (params) {
                    //处理数据
                    this.now = params;
                    this.senderEmailElse = params.senderEmail;
                    this.now.addresseeEmail = this.solveArr(params.addresseeEmail);
                    this.now.emailCarbonCopy = this.solveArr(params.emailCarbonCopy)
                    this.now.emailSecretDelivery = this.solveArr(params.emailSecretDelivery)
                    this.isGroupSend = params.monocular;
                } else {
                    this.now = {
                        addresseeEmail: [],//收件人
                        isCarbonCopy: false,
                        emailCarbonCopy: [],//抄送
                        isSecretDelivery: false,
                        emailSecretDelivery: [],//密送
                        emailSubject: '',//主题
                    }
                    this.senderEmailElse = '';
                    this.isGroupSend = false;
                }
                this.selectEmail = [];
            },
            initSend(senderEmail) {
                this.senderEmailElse = senderEmail;
            },
            initSubject(emailSubject) {
                this.now.emailSubject = emailSubject;
            },
            //获取选择的收件人
            getConcat(title, selectList) {
                //合并数据 - 非群发单显示状态
                this.selectEmail = this.unique(selectList)
                if (title == '收件人') {
                    if (this.selectEmail.length > 0) {
                        this.now.addresseeEmail = this.now.addresseeEmail.concat(this.selectEmail);
                    }
                } else if (title == '抄送') {
                    if (this.selectEmail.length > 0) {
                        this.now.emailCarbonCopy = this.now.emailCarbonCopy.concat(this.selectEmail);
                    }
                } else if (title == '密送') {
                    if (this.selectEmail.length > 0) {
                        this.now.emailSecretDelivery = this.now.emailSecretDelivery.concat(this.selectEmail);
                    }
                }
                this.now.addresseeEmail = this.unique(this.now.addresseeEmail)
                this.now.emailCarbonCopy = this.unique(this.now.emailCarbonCopy)
                this.now.emailSecretDelivery = this.unique(this.now.emailSecretDelivery)
            },
            //预览
            toReview() {
                let param = this.getParam('');
                this.$emit('review', param)
            },
            //提交审批
            toApproval() {
                let param = this.getParam(2);
                delete param.senderEmail;
                this.$emit('toApproval', param)
            },
            //发送邮件
            sendEmail(type) {
                let param = this.getParam(type);
                delete param.senderEmail;
                this.$emit('getInfoWrite', param)
            },
            getParam(type) {
                let addresseeEmail = [], emailCarbonCopy = [], emailSecretDelivery = [];
                this.now.addresseeEmail.map(item => {
                    addresseeEmail.push(item.email)
                })
                this.now.emailCarbonCopy.map(item => {
                    emailCarbonCopy.push(item.email)
                })
                this.now.emailSecretDelivery.map(item => {
                    emailSecretDelivery.push(item.email)
                })
                return Object.assign({}, this.now, {
                    addresseeEmail: addresseeEmail,
                    emailCarbonCopy: emailCarbonCopy,
                    emailSecretDelivery: emailSecretDelivery,
                    monocular: this.isGroupSend ? 1 : 0,
                    sendType: type,
                });
            },
            customerInit(email, emailSubject) {
                this.now.emailSubject = emailSubject;
                email.map(item => {
                    this.now.addresseeEmail.push({linker: '', email: item})
                })
            },
            addUser(title, content) { //receiveUser
                this.isWrong = this.isWrong2=this.isWrong3=false;
                if (content && !validateEmail(content)) {
                    if(title=='收件人'){
                        this.isWrong = true;
                        return;
                    } else if (title == '抄送') {
                        this.isWrong2 = true;
                        return;
                    } else if (title == '密送') {
                        this.isWrong3 = true;
                        return;
                    }
                }
                if (title == '收件人') {//receiveUser
                    if (this.receiveUser != '') {
                        let demo = [{linker: this.receiveUser.split('@')[0], email: this.receiveUser}];
                        this.now.addresseeEmail = this.now.addresseeEmail.concat(demo);
                        this.receiveUser = ''
                    }
                } else if (title == '抄送') {
                    if (this.copyUser != '') {
                        let demo = [{linker: this.copyUser.split('@')[0], email: this.copyUser}];
                        this.now.emailCarbonCopy = this.now.emailCarbonCopy.concat(demo)
                        this.copyUser = ''
                    }
                } else if (title == '密送') {
                    if (this.secretUser != '') {
                        let demo = [{linker:  this.secretUser.split('@')[0], email: this.secretUser}];
                        this.now.emailSecretDelivery = this.now.emailSecretDelivery.concat(demo)
                        this.secretUser = ''
                    }
                }
                this.now.addresseeEmail = this.unique(this.now.addresseeEmail)
                this.now.emailCarbonCopy = this.unique(this.now.emailCarbonCopy)
                this.now.emailSecretDelivery = this.unique(this.now.emailSecretDelivery)
            },
            dealSend(val) {
                this.$emit('getSendEmail', val)
            },
            //群发单显
            groupSend() {
                if (this.isGroupSend) {//取消群发单显
                    this.now = JSON.parse(JSON.stringify(this.old));
                } else {//群发单显
                    this.old = JSON.parse(JSON.stringify(this.now));//保存原数据
                    //处理新数据
                    this.now.isCarbonCopy = this.now.isSecretDelivery = false;
                    this.now.emailCarbonCopy.map(item => {
                        this.now.addresseeEmail.push(item)
                    })
                    this.now.emailSecretDelivery.map(item => {
                        this.now.addresseeEmail.push(item)
                    })
                    this.now.emailCarbonCopy = [];
                    this.now.emailSecretDelivery = [];
                }
                this.isGroupSend = !this.isGroupSend;
            },
            handleClose(item, type) {
                if (type == 1) {
                    this.now.addresseeEmail.splice(this.now.addresseeEmail.indexOf(item), 1);
                } else if (type == 2) {
                    this.now.emailCarbonCopy.splice(this.now.emailCarbonCopy.indexOf(item), 1);
                } else if (type == 3) {
                    this.now.emailSecretDelivery.splice(this.now.emailSecretDelivery.indexOf(item), 1);
                }
                let index = -1;
                this.selectEmail.map((items, i) => {
                    if (items.email == item) {
                        index = i
                    }
                })
                this.selectEmail.splice(index, 1)
            },
            showDialog(type) {
                let arr = [];
                if (type == 1) {//receiveUser
                    arr = this.now.addresseeEmail;
                } else if (type == 2) {
                    arr = this.now.emailCarbonCopy;
                } else if (type == 3) {
                    arr = this.now.emailSecretDelivery;
                }
                this.selectEmail = [];
                this.$refs.dialogConcat.init(type, arr);
            },
            //添加抄送
            ToCarbonCopy() {
                if (this.now.isCarbonCopy) {//取消
                    this.now.emailCarbonCopy = [];
                }
                this.now.isCarbonCopy = !this.now.isCarbonCopy
            },
            //取消抄送
            ToSecretDelivery() {
                if (this.now.isSecretDelivery) {//取消
                    this.now.emailSecretDelivery = [];
                }
                this.now.isSecretDelivery = !this.now.isSecretDelivery
            },
            unique(arr) {
                let hash = [];
                for (let i = 0; i < arr.length; i++) {
                    for (let j = i + 1; j < arr.length; j++) {
                        if (arr[i].email === arr[j].email) {
                            ++i;
                        }
                    }
                    hash.push(arr[i]);
                }
                return hash;
            },
            solveArr(arr) {
                if (arr.length == 0) return [];
                let arrEnd = [];
                arr.map(item => {
                    arrEnd.push({
                        linker: '',
                        email: item
                    })
                })
                return arrEnd;
            },
            cancel() {
                this.isBack = true;
                let param = this.getParam(2);
                this.$emit('getCancel', param)
            },
            querySearch(queryString, cb) {
                if (queryString) {
                    this.getSuggest(1,cb);
                } else {
                    cb([]);
                }
            },
            querySearch2(queryString, cb) {
                if (queryString) {
                    this.getSuggest(2,cb);
                } else {
                    cb([]);
                }
            },
            querySearch3(queryString, cb) {
                if (queryString) {
                    this.getSuggest(3,cb);
                } else {
                    cb([]);
                }
            },
            getSuggest(type,cb){
                let query='';
                if(type==1){
                    query = this.receiveUser;
                }else if(type==2){
                    query = this.copyUser;
                }else{
                    query = this.secretUser;
                }
                getCustomerSuggest(query).then(res => {
                    if (res.data.success) {
                        cb(res.data.data);
                    }
                })
            }
        },
        beforeDestroy() {
            if (!this.isBack) {
                this.bus.$emit('getInfoWrite', this.getParam(2))
            }
        }
    }
</script>

<style lang="scss">
  $lineColor: #F3F3F3;
  $fontColor: #2A97F9;
  .write-top {
    margin-bottom: 15px;

    .el-checkbox__input.is-disabled + span.el-checkbox__label {
      color: #409EFF;
    }

    .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
      background-color: #F2F6FC;
      border-color: #DCDFE6;
    }


    .top-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      .btn-right {
        color: $fontColor;
      }
    }

    .el-form-item.contact {
      .el-table {
        max-height: 300px;
        overflow-y: scroll;
      }

      ul {
        max-height: 300px;
        overflow-y: scroll;

        li {
          line-height: 35px;
          border-bottom: 1px solid #dddddd85;

          i {
            float: right;
            color: transparent;
            font-size: 27px;
            margin-right: 10px;
            cursor: pointer;
          }
        }
      }
    }

    .area-time {
      text-align: right;
      font-size: 12px;
      padding-top: 10px;

      span {
        color: blue;
        cursor: pointer;
        margin-left: 10px;
      }
    }

    .input-add {
      .el-autocomplete {
        input.el-input__inner {
          width: 350px;
        }
      }
    }

    .line {
      display: flex;
      align-items: center;
      font-size: 14px;
      font-weight: normal;
      line-height: 30px;
      padding: 5px 0;
      border-bottom: 1px solid #666;
      overflow: hidden;
      position: relative;

      .line-content {
        display: flex;
        width: 80%;
        align-items: center;
        flex-wrap: wrap;

        .el-tag {
          margin-bottom: 5px;
          font-size: 14px;
        }
      }

      .el-input.el-input--small {
        input.el-input__inner {
          border: 0;
          padding-left: 0;
        }
      }

      span.addMan {
        position: absolute;
        right: 0;
        z-index: 999;
        padding: 0 5px;
        font-size: 12px;
        border: 1px solid #E9F3FD;
        line-height: 24px;
        text-align: center;
        border-radius: 3px;
        color: #2A97F9;
        background-color: #E9F3FD;
        cursor: pointer;
      }

      .label {
        width: 57px;
      }

      b {
        color: #fff;
        padding: 3px 8px;
        border-radius: 3px;
        background-color: #2a97f9;
        font-size: 12px;
        font-weight: normal;
        cursor: pointer;
      }

      input[type="text"].myInput {
        color: #333;
        height: 40px;
        line-height: 40px;
        border: 0;
        width: 90%;
        background-color: transparent;
      }

      i.add-icon {
        float: right;
        line-height: 40px;
        font-size: 25px;
        color: #333;
        cursor: pointer;
      }

      span.el-tag {
        padding: 0 5px;
        height: 25px;
        line-height: 25px;
        margin-right: 10px;
      }

    }

  }
</style>
